package com.xiao.xin.comfyui.client.config;

import com.xiao.xin.comfyui.client.api.ComfyuiApi;
import com.xiao.xin.comfyui.client.handler.ComfyuiMessageHandler;
import com.xiao.xin.core.common.Constants;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.time.Duration;

/***
 * 配置ComfyUI
 */
@Configuration
public class ComfyuiConfig {


    /***
     * 配置Retrofit
     * @return
     */
    @Bean
    public ComfyuiApi comfyuiApi() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 设置OkHttp日志级别

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .connectTimeout(Duration.ofSeconds(30)) // 设置连接超时时间
                .readTimeout(Duration.ofSeconds(30)) // 设置读取超时时间
                .retryOnConnectionFailure(true)
                .build();
        Retrofit retrofit = new Retrofit
                .Builder()
                .client(client)
                .baseUrl("http://192.168.100.129:8188/")
                .addConverterFactory(JacksonConverterFactory.create()) // 使用Jack工具包处理Json数据
                .build();
        return retrofit.create(ComfyuiApi.class); // 让retrofit帮我实现接口
    }

    /***
     * 配置SpringWebSocket客户端连接
     * @param comfyuiMessageHandler
     * @return
     */
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {
        WebSocketClient client = new StandardWebSocketClient();
        String url = "ws://192.168.100.129:8188/ws?clientId=" + Constants.COMFYUI_CLIENT_ID;
        WebSocketConnectionManager manager = new WebSocketConnectionManager(client, comfyuiMessageHandler, url);
        manager.start();
        return manager;
    }

}

